package com.cheng.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * User: cheng
 * Date: 2014/4/24
 * Time: 16:42
 */
public class ExecutorsTest {

    public static void newSingleThreadExecutorTest(){
        ExecutorService pool = Executors.newSingleThreadExecutor();
        System.out.println("=============newSingleThreadExecutor================");
        for(int i = 0;i < 10;i++){
            pool.submit(new MyThread(4));
        }
    }

    public static void newFixedThreadPoolTest(){
        ExecutorService pool = Executors.newFixedThreadPool(2);
        System.out.println("=============newFixedThreadPool================");
        for(int i = 0;i < 10;i++){
            pool.submit(new MyThread(5));
        }
    }

    public static void newCachedThreadPoolTest(){
        ExecutorService pool = Executors.newCachedThreadPool();
        System.out.println("=============newCachedThreadPool================");
        for(int i = 0;i < 10;i++){
            pool.submit(new MyThread(6));
        }
    }

    public static void ScheduledThreadPoolExecutorTest(){
        ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(3);
        System.out.println("=============ScheduledThreadPoolExecutor================");
        exec.scheduleAtFixedRate(new MyThread(1),1000,1000, TimeUnit.MILLISECONDS);
        exec.scheduleAtFixedRate(new MyThread(2),1000,2000, TimeUnit.MILLISECONDS);
        exec.scheduleAtFixedRate(new MyThread(3),1000,3000, TimeUnit.MILLISECONDS);
    }

    public static void main(String[] args) {
        newSingleThreadExecutorTest();
        newFixedThreadPoolTest();
        newCachedThreadPoolTest();
        ScheduledThreadPoolExecutorTest();
    }

}

class MyThread extends Thread{
    private int i;
    public MyThread(int i){
        this.i = i;
    }
    public void run(){
        System.out.println(Thread.currentThread().getName() + "正在执行..." + i);
    }
}
